﻿
using EntityModel.Helper;
using EntityModel.PageListInfor;
using EntityModel.Procurement;
using IServices.ICurrency;
using IServices.IStock;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services.Stock
{

    public class Stock : IStock
    {
        private readonly RoutineDbContext _dbContext;
        private readonly ICurrencyServer _currencyServer;
        private readonly IConfiguration _configuration;
        public Stock(RoutineDbContext dbContext, ICurrencyServer currencyServer, IConfiguration configuration)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
            _currencyServer = currencyServer ?? throw new ArgumentNullException(nameof(currencyServer));
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
        }

        /// <summary>
        /// 添加采购单数据
        /// </summary>
        /// <param name="_Stocks">采购单集合</param>
        /// <returns></returns>
        public async Task<bool> AddStocksAsync(AikeApplet_Stocks _Stocks)
        {
            var stockid = string.Empty;
            var count = string.Empty;
            if (_Stocks == null) throw new ArgumentNullException(nameof(_Stocks));
            if (_Stocks.stockid == null || _Stocks.stockid == "")
            {
                #region 获取当天添加的数据量
                var data = _currencyServer.ExecuteSqlAsync(_configuration.GetConnectionString("DefaultConnection"), "SELECT top 1 Amount FROM Stocks WHERE CONVERT (CHAR(8),stockDate,112)=CONVERT(CHAR(8),GETDATE(),112) order by stockDate desc");
                if (data.Rows.Count == 0) stockid = "CG" + DateTime.Now.ToString("yyyymmdd") + "0001";
                foreach (DataRow item in data.Rows)
                {
                    var Amounts = (Convert.ToInt32(item["Amount"].ToString().PadLeft(4, '0')) + 1).ToString().PadLeft(4, '0');
                    stockid = "CG" + DateTime.Now.ToString("yyyymmdd") + Amounts;
                    count = Amounts;
                }
                #endregion
            }
            await _dbContext._Stocks.AddAsync(new AikeApplet_Stocks
            {
                stockid = stockid,  //采购单编号
                ppid = _Stocks.ppid,    //供货商编号
                stockDesc = _Stocks.stockDesc,  //备注
                stockDate = DateTime.Now,   //下单时间
                stockInDate = _Stocks.stockInDate,  //预计交货时间
                stockState = _Stocks.stockState,
                stockUser = 1,  //创建人
                Amount = count  //总数
            });
            return await _dbContext.SaveChangesAsync() >= 0;
        }

        /// <summary>
        /// 删除采购单数据
        /// </summary>
        /// <param name="StockID">采购单编号</param>
        /// <returns></returns>
        public async Task<bool> DeletedStocksAsync(AikeApplet_Stocks StockID)
        {
            if (StockID == null) throw new ArgumentNullException(nameof(StockID));

            _dbContext._Stocks.Remove(StockID);

            return await _dbContext.SaveChangesAsync() >= 0;
        }

        /// <summary>
        /// 获取采购单数据
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<AikeApplet_Stocks>> GetAllStockDataAsync()
        {
            return await _dbContext._Stocks.AsQueryable().ToListAsync();
        }

        /// <summary>
        /// 通过采购单编号获取数据
        /// </summary>
        /// <param name="StockID">采购单编号</param>
        /// <returns></returns>
        public async Task<AikeApplet_Stocks> GetEntityStockAsync(string StockID)
        {
            if (StockID == null) throw new ArgumentNullException(nameof(StockID));
            var result = await _dbContext._Stocks.FirstOrDefaultAsync(x => x.stockid == StockID);
            return result;
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="aikeApplet"></param>
        /// <returns></returns>
        public Task<DbQueryResult> GetPageListStockAsync(AikeApplet_Stocks aikeApplet)
            {
            StringBuilder sb = new StringBuilder();
            //SqlCommand cmd = new SqlCommand(connection,);
            if (!string.IsNullOrEmpty(aikeApplet.stockid))
            {
                sb.Append($" stockid like '%{ aikeApplet.stockid}%'");
            }
            if (!string.IsNullOrEmpty(aikeApplet.ppid))
            {
                sb.Append($" and ppid like '%{aikeApplet.ppid}%'");
            }
            if (aikeApplet.stockDate != DateTime.MinValue)
            {
                sb.Append($" and stockDate = '{aikeApplet.stockDate}'");
            }
            if (aikeApplet.stockInDate != DateTime.MinValue)
            {
                sb.Append($" and stockInDate = '{aikeApplet.stockInDate}'");
            }
            return _currencyServer.PagingByRownumber("Stocks", "stockid", aikeApplet.PageIndex, aikeApplet.PageSize
                , aikeApplet.SortBy, aikeApplet.SortOrder, sb.ToString(), true, "*");
        }

        /// <summary>
        /// 判断采购单是否存在
        /// </summary>
        /// <param name="StockID"></param>
        /// <returns></returns>
        public async Task<bool> IsExistStocksAsync(string StockID)
        {
            if (StockID == null) throw new ArgumentNullException(nameof(StockID));

            return await _dbContext._Stocks.AnyAsync(x => x.stockid == StockID);
        }

        /// <summary>
        /// 修改采购单数据
        /// </summary>
        /// <param name="aikeApplet_Stocks">采购单数据集</param>
        /// <returns></returns>
        public async Task<bool> UpdateStocksAsync(AikeApplet_Stocks aikeApplet_Stocks)
        {
            if (aikeApplet_Stocks == null) throw new ArgumentNullException(nameof(aikeApplet_Stocks));
            AikeApplet_Stocks data = await GetEntityStockAsync(aikeApplet_Stocks.stockid);
            if (data == null) throw new ArgumentNullException(nameof(data));
            data.stockid = aikeApplet_Stocks.stockid;
            data.ppid = aikeApplet_Stocks.ppid;
            data.stockDate = aikeApplet_Stocks.stockDate;
            data.stockDesc = aikeApplet_Stocks.stockDesc;
            data.stockInDate = aikeApplet_Stocks.stockInDate;
            data.stockState = aikeApplet_Stocks.stockState;
            data.stockUser = aikeApplet_Stocks.stockUser;

            _dbContext._Stocks.Update(data);
            return await _dbContext.SaveChangesAsync() >= 0;
        }
    }
}
